package team.lourd.network.system.querydsl;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
import org.springframework.data.jpa.repository.support.JpaRepositoryFactoryBean;
import org.springframework.data.repository.core.RepositoryMetadata;
import org.springframework.data.repository.core.support.RepositoryFactorySupport;

import javax.persistence.EntityManager;
import java.io.Serializable;

/**
* @Description:  创建动态查询语句的Repository 工厂类
* @Author: Lourd
* @Date: 2019/1/17
*/
public class ExtendedQuerydslJpaRepositoryFactoryBean<R extends JpaRepository<T, I>, T, I extends Serializable> extends JpaRepositoryFactoryBean<R, T, I> {

    public ExtendedQuerydslJpaRepositoryFactoryBean(Class<? extends R> repositoryInterface) {
        super(repositoryInterface);
    }
    protected RepositoryFactorySupport createRepositoryFactory(final EntityManager entityManager){
        return new ExtendedQuerydslJpaRepositoryFactory(entityManager);
    }
    private static class ExtendedQuerydslJpaRepositoryFactory<T,I extends Serializable> extends JpaRepositoryFactory {
        private EntityManager entityManager;

        public ExtendedQuerydslJpaRepositoryFactory(EntityManager entityManager){
            super(entityManager);
            this.entityManager=entityManager;
        }
        protected Object getTargetRepository(RepositoryMetadata metadata){
            return new ExtendedQuerydslJpaRepositoryImpl<>(getEntityInformation(metadata.getDomainType()),entityManager);
        }
        protected Class<?> getRepositoryBaseClass(RepositoryMetadata metadata){
            return ExtendedQuerydslJpaRepositoryImpl.class;
        }
    }
}
